<script setup>
import {nextTick, reactive, ref, watch} from "vue";
import local from "@/axios/local";
import {ElLoading, ElMessage} from "element-plus";
import utils from "@/utils/storage";
const loading = ref(false)
const emits = defineEmits(['success', 'task_success'])
const rules = {
  file: {
    required: true,
    message: '请上传文件',
    trigger: 'change'
  },
  name: {
    required: true,
    message: '请输入文件夹名称',
    trigger: 'blur'
  }
}
const form = reactive({
  fileList: [],
  desc: '',
  file: '',
  parent_id: null,
  is_folder: 0,
  name: '',
  type: '',
  size: '',
})
const props = defineProps(['file_type', 'file_path'])
import socket from '@/utils/socket'
import {invoke} from "@/utils/ipc_fn";

const showDialog = ref(false)
const upload = ref()
const formRef = ref()
const type = ref('')
const Socket = new socket()

function title() {
  if (type.value === 'file') {
    return '上传文件'
  } else {
    return '新建文件夹'
  }
}

function show(t, id) {
  type.value = t
  form.parent_id = id
  form.fileList = []
  form.name = ''
  form.desc = ''
  form.file = null
  showDialog.value = true

}

function beforeUpload(file) {
  console.log(file)
  form.file = file
  form.fileList = [
    {
      name: form.file.name
    }
  ]
  return false
}

function beforeUploadDict() {
  // 选择文件夹
  invoke('selectFolder', '').then(r => {
    if(!r) return
    console.log(r)
    form.folder_path = r
    form.name = r.split('\\')[r.split('\\').length - 1]
  })
}

function handleExceed(files) {
  upload.value.clearFiles()
  const file = files[0]
  upload.value.handleStart(file)
}

function compareSize(file, mb) {
  const MAX_SIZE = mb * 1024 * 1024; // 50MB，单位是字节
  return file.size > MAX_SIZE;
}

function submit() {
  formRef.value.validate((v) => {
    if (v) {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      let formData = new FormData()
      if (form.file) {
        form.name = form.file.name
        form.size = form.file.size
        if (utils.returnFileType('图片', form.file.name)) {
          form.type = 'image'
        } else if (utils.returnFileType('文档', form.file.name)) {
          form.type = 'doc'
        } else if (utils.returnFileType('视频', form.file.name)) {
          form.type = 'video'
        } else if (utils.returnFileType('音频', form.file.name)) {
          form.type = 'audio'
        } else if (utils.returnFileType('文本', form.file.name)) {
          form.type = 'text'
        } else {
          form.type = 'other'
        }
      } else {
        form.size = ''
        form.type = ''
      }
      form.is_folder = type.value === 'file' ? 0 : 1
      if (form.file) formData.append('file', form.file)

      const userInfo = utils.get('userInfo', 'json')
      if (userInfo.id) formData.append('create_by', userInfo.id)
      if (form.name) formData.append('name', form.name)
      if (form.size) formData.append('size', form.size)
      if (form.folder_path) formData.append('folder_path', form.folder_path)
      if (form.type) formData.append('type', form.type)
      if (form.is_folder) formData.append('is_folder', form.is_folder)
      if (form.desc) formData.append('desc', form.desc)
      formData.append('file_path', [...props.file_path.map(el => el.name), form.name].join('/'))
      if (form.parent_id) {
        formData.append('parent_id', form.parent_id)
      }
      // if (form.file && compareSize(form.file, 30)) {
      //   local.post('/cloud/uploadChunkFile', formData, {
      //     headers: {
      //       'content-type': 'multipart/form-data'
      //     }
      //   }).then(res => {
      //     ElMessage.success('任务已提交')
      //     showDialog.value = false
      //     emits('task_success', res.data)
      //   })
      //   return
      // }
      local.post('/cloud/createFileOrFolder', formData, {
        headers: {
          'content-type': 'multipart/form-data'
        }
      }).then(res => {
        ElMessage.success('操作成功')
        showDialog.value = false
        emits('success')
        loading.close()
      }).catch(err => {
        loading.close()
      })

    }
  })
}

defineExpose({
  show
})
</script>

<template>
  <div>
    <el-dialog :loading="loading" draggable width="700px" v-model="showDialog" :title="title()">
      <el-form ref="formRef" :rules="rules" label-width="100px" :model="form">
        <el-form-item label="上传类型">
          <el-radio-group v-model="type">
            <el-radio label="file">文件</el-radio>
            <el-radio label="folder">文件夹</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="type==='file'">
          <el-form-item label="文件" prop="file">
            <el-upload
                :file-list="form.fileList"
                ref="upload"
                class="upload-demo"
                :before-upload="beforeUpload"
                action=""
                :limit="1"
                :on-exceed="handleExceed"
                :auto-upload="true"
            >
              <template #trigger>
                <el-button type="primary">点击上传</el-button>
              </template>
            </el-upload>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="文件夹" prop="folder_path">
            <el-button @click="beforeUploadDict">选择文件夹</el-button>
          </el-form-item>
          <el-form-item label="文件夹名称" prop="name">
            <el-input :disabled="form.folder_path" v-model="form.name" maxlength="255" show-word-limit
                      clearable></el-input>
          </el-form-item>
        </template>
        <el-form-item label="描述" prop="desc">
          <el-input :rows="4" v-model="form.desc" maxlength="255" show-word-limit type="textarea"
                    clearable></el-input>
        </el-form-item>

      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button @click="submit" type="primary">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.upload-demo {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  ::v-deep(.el-upload-list) {
    width: 100%;
    display: flex;
    justify-content: flex-start;

    .el-upload-list__item-info {
      width: 100%;
    }
  }
}

::v-deep(.el-upload) {
  display: flex;
  justify-content: flex-start;
  width: 100%;

  .el-upload-dragger {
    width: 100%;
  }
}
</style>
